﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a can open array
    /// </summary>
    /// <typeparam name="T">
    /// Type
    /// </typeparam>
    public class CanOpenArray<T> : ReadOnlyCollection<ICanOpenValueObject>, ICanOpenDataFieldObject where T : ICanOpenValueObject
    {

        /// <summary>
        /// Initializes a new instance of the CanOpenArray class by the given
        /// parameter
        /// </summary>
        /// <param name="firstValueObject">
        /// First value object (at sub index 0)
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Will be thrown if the first value object is null
        /// </exception>
        public CanOpenArray(CanOpenUnsigned8 firstValueObject)
            : this(firstValueObject, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the CanOpenArray class by the given
        /// parameter
        /// </summary>
        /// <param name="firstValueObject">
        /// First value object (at sub index 0)
        /// </param>
        /// <param name="valueObjects">
        /// List of value objects (at sub index 1..255) or null
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// Will be thrown if the first value object is null
        /// </exception>
        /// <exception cref="ArgumentException">
        /// Will be thrown if the value objects list contains more than 255
        /// items
        /// </exception>
        public CanOpenArray(CanOpenUnsigned8 firstValueObject, IList<T> valueObjects)
            : base(new List<ICanOpenValueObject>())
        {
            // check parameter
            if (firstValueObject == null)
            {
                throw new ArgumentNullException("firstValueObject", "The first value object must not be null");
            }
            if (valueObjects != null && valueObjects.Count >= 256)
            {
                throw new ArgumentException("Size of the value objects list must be less than 255 items", "valueObjects");
            }

            // initialization
            Items.Add(firstValueObject);
            if (valueObjects != null)
            {
                for (int i = 0; i < Math.Min(valueObjects.Count, 255); i++)
                {
                    Items.Add(valueObjects[i]);
                }
            }
        }

    }

}
